#!/bin/bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2024 Huawei Technologies Co., Ltd. All rights reserved.

repos_list_file=$1

loop_convert_repos()
{
	while read rpm_repo_path result_repo_path
	do
		# for comment line
		[[ ${rpm_repo_path} =~ ^\ *#.*$ ]] && continue
		# for empty lines
		[[ -z ${rpm_repo_path} ]] && continue

		[[ -z ${result_repo_path} ]] && {
			echo "Rpm repo path not specified for ${rpm_repo_path}"
			continue
		}

		loop_convert_epkg ${rpm_repo_path/%\/Packages\/*/''} ${result_repo_path}

		create_epkg_repo $result_repo_path
	done < ${repos_list_file}
}

loop_convert_epkg()
{
	local rpm_repo=$1
	local result_repo_path=$2

	[[ -d ${result_repo_path}/store ]] || {
		mkdir -p ${result_repo_path}/store
	}

	for rpm in $(find ${rpm_repo} -name "*.rpm")
	do
		[[ $rpm =~ '.rpm' ]] || continue
		[[ $rpm =~ 'src.rpm' ]] && continue

		echo "converting rpm:	${rpm}"

		./convert-rpm2epkg ${rpm} ${result_repo_path}
	done
}

create_epkg_repo()
{
	local repo_path=$1

	[[ -z $(find ${repo_path}/store -name *.epkg -exec echo {} \; -quit) ]] && {
		echo "No epkg package found!"
		echo "Please correct the repo path and try again!"

		exit 1
	}

	# clean outdated repo metadata
	rm -rf ${repo_path}/{pkg-info,pkg-info.zst,repodata,metadata.json} 2>/dev/null

	# re-init repo metadata dir tree
	mkdir -p ${repo_path}/{pkg-info,repodata}
	touch ${repo_path}/repodata/index.yaml

	for epkg_file in $(find ${repo_path}/store -name *.epkg)
	do
		epkg_file_name=$(basename ${epkg_file})
		epkgs_metadata_path=${repo_path}/pkg-info/${epkg_file_name:0:2}/
		mkdir -p ${epkgs_metadata_path}

		epkgs_metadata_file=${repo_path}/pkg-info/${epkg_file_name:0:2}/${epkg_file_name%.*}.json
		repodata_dir=${repo_path}/repodata
		initial_release_file=${repodata_dir}/store-paths
		mkdir -p ${repodata_dir}

		echo ${epkg_file_name%.*} >> ${initial_release_file}
		tar --use-compress-program=zstd -xf ${epkg_file} -O ./info/package.json --strip-components=2 > ${epkgs_metadata_file}
	done

	tar --use-compress-program=zstd -cf ${repo_path}/repodata/pkg-info.zst -C ${repo_path} pkg-info
	zstd --rm ${initial_release_file}
}

[[ -z $repos_list_file ]] && {
	echo "Please specify the repo list file."
	echo "the file content line should be like:"
	echo "	'''"
	echo '	${repo_url1} ${local_repo_path1}'
	echo '	${repo_url2} ${local_repo_path2}'
	echo "	... ..."
	echo "	'''"

	exit 1
}

loop_convert_repos
wait
